import json

from django.http import JsonResponse
from web.models import LoanOrder
import hashlib
import requests
import time
def generate_sign(params, key="Kqz8C8zcj1Qc8LAKt8fCHUpAPHqc11Th"):
    """
    根据给定的参数和密钥生成MD5签名
    :param params: 包含参数的字典，例如 {"a": "1", "b": "2"}
    :param key: 商户密钥，字符串类型
    :return: 生成的MD5签名，小写字符串
    """

    # 过滤掉sign、sign_type和值为空的参数
    filtered_params = {k: v for k, v in params.items() if k not in ["sign", "sign_type"] and v}
    # 按照参数名ASCII码从小到大排序
    sorted_params = sorted(filtered_params.items(), key=lambda x: x[0])
    # 拼接成URL键值对的格式
    param_str = "&".join([f"{k}={v}" for k, v in sorted_params])
    # 与商户密钥拼接后进行MD5加密
    md5_str = param_str + key
    md5 = hashlib.md5()
    md5.update(md5_str.encode('utf-8'))
    return md5.hexdigest().lower()

pay_url = "https://yi-pay.com/mapi.php"

# 异步通知接口
def notify(request):
    print("接收到请求", request.GET)
    print("接收到请求", request.GET["param"])
    return JsonResponse("success", safe=False)


# 支付接口
"""
pay_type: 
    0: 还款
"""
def pay(request):
    if request.method == "POST":
        data = {
            "pid": "2704",
            "type": "alipay",
            "out_trade_no": "EloanCloud__" + str(int(time.time())),
            "notify_url": "http://2fer2m.natappfree.cc/api/pay/notify/",
            "name": "测试支付",
            "money": request.POST.get("money"),
            "clientip": request.META.get("REMOTE_ADDR"),
            "sign": "",
            "sign_type": "MD5",
            "param": f"loan_order_number={request.POST.get("loan_order_number")}|pay_type={request.POST.get("pay_type")}"
        }

        data["sign"] = generate_sign(data)
        response = requests.post(pay_url, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}).json()
        print(response)
        return JsonResponse({"code": 0, "msg": "ok", "data": response})


# 是否完成支付接口
def is_pay(request):
    if request.method == "POST":
        ord = LoanOrder.objects.filter(loan_order_number=request.POST.get("loan_order_number")).first()
        if not ord:
            return JsonResponse({"code": 400, "msg": "订单不存在"})
        return JsonResponse({"code": 200, "msg": "ok", "data": ord.status})


